package plugin;

import controllers.BaseController;
import duppentity.Dupps;
import groovy.lang.Closure;
import play.Logger;
import play.Play;
import play.exceptions.TagInternalException;
import play.exceptions.TemplateExecutionException;
import play.libs.IO;
import play.mvc.Router;
import play.templates.FastTags;
import play.templates.GroovyTemplate;
import play.vfs.VirtualFile;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 页面所需的标签,放入此类
 * @author zhangzc@djcars.cn
 */
public class XTag extends FastTags {

    private static final Map<String, String> hrefCache = new ConcurrentHashMap();
    private static ThreadLocal<SimpleDateFormat> fileSigFormat = new ThreadLocal();

    public static void _href(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine){
        if (!args.containsKey("arg") || args.get("arg") == null) {
            // do nothing
            return;
        }
        String action = (String) args.get("arg");
        try{

            VirtualFile file = Play.getVirtualFile(action);
            if(!file.exists()){
                Logger.warn("Can't find static file: %s", action);
                out.write(action);
                return;
            }
            String href = Router.reverseWithCheck(action, file, false);
            // search from local cache
            String fileSig = hrefCache.get(action);
            if(StringUtils.isEmpty(fileSig)){ // when not found
                SimpleDateFormat sdf = fileSigFormat.get();
                if(sdf == null){
                    sdf = new SimpleDateFormat("yyyyMMddHHmm");
                    fileSigFormat.set(sdf);
                }
                fileSig = sdf.format(new Date(file.lastModified()));
                // save to local cache
                hrefCache.put(action, fileSig);
            }
            out.write(href);
            if(StringUtils.contains(href, "?")){
                out.write("&t=");
            }else{
                out.write("?t=");
            }
            out.write(fileSig);
        }catch (Exception e){
            Logger.error(e, "Error in generating href: %s", action);
            out.write(action);
        }
    }

    private static final Map<String, String> outputCache = new ConcurrentHashMap();

    /**
     * 输出静态文件，用于避免引擎解析的文本输出
     *
     * @param args
     * @param body
     * @param out
     * @param template
     * @param fromLine
     */
    public static void _output(Map<?, ?> args, Closure body, PrintWriter out, GroovyTemplate.ExecutableTemplate template, int fromLine) {
        if (!args.containsKey("arg") || args.get("arg") == null) {
            throw new TemplateExecutionException(template.template, fromLine, "Specify a file name",
                    new TagInternalException("Specify a file name"));
        }
        String filePath = args.get("arg").toString();
        String filePathInProject = "app/views/" + filePath;
        try {
            String key = "OutputFile-" + filePathInProject;
            String content = outputCache.get(key);
            if (StringUtils.isEmpty(content)) {
                File file = Play.getVirtualFile(filePathInProject).getRealFile();
                content = IO.readContentAsString(file);
                if (Play.mode.isProd()) {
                    outputCache.put(key, content);
                }
            }
            out.write(content);
        } catch (Exception e) {
            Logger.error(e, "Cannot output %s", filePath);
            out.write(String.format("<!--Cannot output: %s-->", filePath));
        }
    }
}
